import { defineStore } from "pinia";
import { ref } from "vue";


const STORAGE_KEY = 'user_data'
const DEFAULT_ADMIN ={
    id :'admin',
    username: 'admin',
    password: 'admin123',
    role: 'admin',
    name: '系统管理员'
}

const loadUsers = () => {
    const storedData = localStorage.getItem(STORAGE_KEY)
    const users = storedData ? JSON.parse(storedData) : []

    if (!users.some(user => user.role === 'admin')){
        users.push(DEFAULT_ADMIN)
        saveUsers(users)
    }
    return users
}


const saveUsers = (users) => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(users))
}

export const useMemberStore = defineStore('member', () => {
    const users = ref(loadUsers())

    const addUser = (user) => {
        user.id = Date.now()
        if (user.role === 'teacher'){
            user.subjects = []
        }
        user.grades = {
            frontend: null,
            english: null,
            python: null
        }
        users.value.push(user)
        saveUsers(users.value)
    }

    const updateUser =(id, updatedInfo) =>{
        const user = users.value.find((u) =>u.id === id)
        if (user){
            Object.assign(user, updatedInfo)
            saveUsers(users.value)
        }
    }

    const updateStudentGrades = (id, grades) => {
        const student = users.value.find((u) => u.id === id && u.role === 'student')
        if(student){
            student.grades = {...student.grades, ...grades}
            saveUsers(users.value)
        }
    }

    const getUserById = (id) => {
        return users.value.find((u) => u.id === id)
    }
    const getUserByUsername = (username) => {
        return users.value.find((u) => u.username === username)
    }
    const deleteUser =(id) => {
        users.value = users.value.filter((u) => u.id !== id)
        saveUsers(users.value)
    }

    const getAllStudents = () => {
        return users.value.filter((u) => u.role === 'student')
    }

    const updateTeacherSubjects = (id, subjects) => {
        const teacher = users.value.find((u) => u.id === id && u.role === 'teacher')
        if(teacher) {
            teacher.subjects = subjects
            saveUsers(users.value)
        }
    }
    return{
        users,
        addUser,
        getUserById,
        getUserByUsername,
        deleteUser,
        getAllStudents,
        updateStudentGrades,
        updateTeacherSubjects
    }
})